import { SpriteFrame } from 'cc'

const INDEX_REG = /\((\d+)\)/

const getNumberWithinString = (str: string) => parseInt(str.match(INDEX_REG)?.[1] || '0')

export const sortSpriteFrame = (spriteFrame: Array<SpriteFrame>) =>
  spriteFrame.sort((a, b) => getNumberWithinString(a.name) - getNumberWithinString(b.name))

export const rad2Angle = (rad: number) => {
  return (rad / Math.PI) * 180
}

export function deepClone<T>(target: T): T {
  // 处理null或undefined
  if (target === null || target === undefined) {
    return target
  }

  // 处理日期对象
  if (target instanceof Date) {
    return new Date(target.getTime()) as any
  }

  // 处理正则表达式
  if (target instanceof RegExp) {
    return new RegExp(target.source, target.flags) as any
  }

  // 处理Map
  if (target instanceof Map) {
    const result = new Map()
    target.forEach((value, key) => {
      result.set(deepClone(key), deepClone(value))
    })
    return result as any
  }

  // 处理Set
  if (target instanceof Set) {
    const result = new Set()
    target.forEach(value => {
      result.add(deepClone(value))
    })
    return result as any
  }

  // 处理数组和对象
  if (typeof target === 'object') {
    if (Array.isArray(target)) {
      return target.map(item => deepClone(item)) as any
    }
    const result: Record<string, any> = {}
    for (const key in target) {
      if (Object.prototype.hasOwnProperty.call(target, key)) {
        result[key] = deepClone(target[key])
      }
    }
    return result as T
  }

  // 处理基本类型
  return target
}

export const randomBySeed = (seed: number) => {
  return (seed * 9301 + 49297) % 233280
}
